package com.well.rpc.event;

import com.alibaba.fastjson.JSONArray;
import com.well.rpc.config.ClientDataConfig;
import com.well.rpc.model.EventType;
import com.well.rpc.model.RegisterModel;
import com.well.rpc.model.TransData;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
public class RegisterResponseEvent implements AppEvent {

    @Override
    @PostConstruct
    public void addEvent() {
        EventContext.setEvent(EventType.REGISTER_RESPONSE, this);
    }

    @Override
    public void doEvent(ChannelHandlerContext channelHandlerContext, TransData transData) {
        String jsonData = transData.getJsonData();
        List<RegisterModel> serverModels = JSONArray.parseArray(jsonData, RegisterModel.class);
        ClientDataConfig.setRegisterModels(serverModels);
        if (!ClientDataConfig.getClientRegisterStatus()) {
            ClientDataConfig.setClientRegisterStatus(true);
            log.info("RPC server is registered!");
        }
        log.info("Data Transfer Success.");
    }

    @Override
    public EventType eventType() {
        return EventType.REGISTER_RESPONSE;
    }

    @Override
    public void errorEvent(ChannelHandlerContext channelHandlerContext, Throwable cause) {
        ClientDataConfig.isStart = false;
        log.error("server is registered fail");
        channelHandlerContext.channel().close();
    }
}
